package com.school.door;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import com.alibaba.fastjson.JSON;
import com.mhuang.school.starter.minio.core.MinioFrame;
import com.mhuang.school.starter.minio.util.ToolUtil;
import com.school.device.config.DahuaCofig;
import com.school.device.config.DoorConfig;
import com.school.device.dynamic.DvIntellifHikvisonDevice;
import com.school.device.util.DataConvertUtil;
import com.school.device.util.JsonUtil;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Component
public class DoorSchedule {	
	
	private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//2025/01/23 03:42:35
	
	@Autowired
	private DoorConfig doorConfig;
	
	@Autowired
	private DahuaCofig dahuaCofig;
	
	@Autowired
	private MinioFrame minioFrame;
		
	private final static Map<String,String> userIdHeads=new ConcurrentHashMap<String, String>();
	private final static Map<String,Long> deviceIdDates=new ConcurrentHashMap<String, Long>();	
	private final static Map<String,Integer> ipStatus=new ConcurrentHashMap<String, Integer>();
	

	public static void main(String[] args) {
	}

	private final TaskScheduler taskScheduler;
    private ScheduledFuture<?> scheduledFuture;

    public DoorSchedule(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    @PostConstruct
    public void init() {
        scheduledFuture = taskScheduler.schedule(() -> {//此处为执行任务
        	List<DvIntellifHikvisonDevice> devices= getDevices();
        	//获取设备ips
        	String deviceIps=devices.stream().filter(item->(item.getDeviceType()==5)).map(DvIntellifHikvisonDevice::getDeviceIp).filter(ip->ToolUtil.isNotEmpty(ip)).collect(Collectors.joining(","));//可能发生变化
        	if(ToolUtil.isNotEmpty(deviceIps)) {
            	//获取最近状态
            	getUserIdDatas(deviceIps);
            	//执行单个单个拉取
            	List<Map<String, Object>> result=new ArrayList<Map<String,Object>>();
            	for(DvIntellifHikvisonDevice device:devices) {
            		String deviceIp=device.getDeviceIp();
            		Long latestDate=deviceIdDates.get(deviceIp);      		
            		List<Map<String, Object>> datas=getDatas(device);
            		if(datas!=null && datas.size()>0) {
    	        		for(Map<String, Object> data:datas) {
    	        			Long cardTime = null;
    						try {
    							cardTime = dateFormat.parse(String.valueOf(data.get("cardTime"))).getTime();
    							data.put("cardTime", cardTime);
    		        			if((latestDate!=null && latestDate<cardTime) || (latestDate==null))
    		        				result.add(data);
    						} catch (ParseException e) {
    							e.printStackTrace();
    						}
    	        		}
    	            	sendStatus(device.getDeviceIp());
            		}
            		try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
            	}
            	if(result!=null && result.size()>0) {
            		sendData(result);
            		log.info("一次定时任务执行完成,写入数据:"+result.size());
            	}
        	}
        }, new CronTrigger(doorConfig.getCronExpress())); // 每5秒执行一次
    }

    @PreDestroy
    public void destroy() {
        if (scheduledFuture != null) 
            scheduledFuture.cancel(true);
    }
    
    //获取所有设备(需要间隔5分钟)
	private List<DvIntellifHikvisonDevice> getDevices() {
		String deviceIpUrl=dahuaCofig.getDeviceipUrl();
		if (ToolUtil.isEmpty(deviceIpUrl)) {
			System.err.println("拉取设备端口接口为空");
			log.error("拉取设备端口接口为空");
			return null;
		}
		HttpResponse response = HttpRequest.get(deviceIpUrl).execute();
		if (response.isOk()) {
			String body = response.body();
			if (ToolUtil.isNotEmpty(body)) {
				Map<String, Object> result = JsonUtil.toMap(body);
				if (DataConvertUtil.getObjectStr(result, "respCode").equalsIgnoreCase("10000000"))
					return JsonUtil.toBeans(JSON.toJSONString(result.get("data")), DvIntellifHikvisonDevice.class);
			}
		}
		System.err.println("请检查连接设备端口");
		log.error("请检查连接设备端口");
		return null;
	}
	
	//获取设备最近状态
	private List<AiAccessDoorRecord> getLatestStatus(String deviceIps){
		if (ToolUtil.isEmpty(deviceIps)) {
			System.err.println("拉取不到相关的门禁设备");
			log.error("拉取不到相关的门禁设备");
			return null;
		}
		HttpResponse response = HttpRequest.get(doorConfig.getCheckUrl()+"?deviceIps="+deviceIps).execute();
		if (response.isOk()) {
			String body = response.body();
			if (ToolUtil.isNotEmpty(body)) {
				Map<String, Object> result = JsonUtil.toMap(body);
				if (DataConvertUtil.getObjectStr(result, "respCode").equalsIgnoreCase("10000000"))
					return JsonUtil.toBeans(JSON.toJSONString(result.get("data")), AiAccessDoorRecord.class);
			}
		}
		System.err.println("请检查连接设备端口");
		log.error("请检查连接设备端口");
		return null;		
	}
	
	private void getUserIdDatas(String deviceIps){
		List<AiAccessDoorRecord> datas=getLatestStatus(deviceIps);
		if(datas==null)
			return;
		datas.stream().forEach((item)->{
			String deviceId=item.getDeviceIp();
			Long cardTime=item.getCardTime();
			if(!deviceIdDates.containsKey(deviceId)) {
				deviceIdDates.put(deviceId, cardTime);
			}else {
				Long ocardTime=deviceIdDates.get(deviceId);
				if(cardTime.compareTo(ocardTime)>0)
					deviceIdDates.put(deviceId, cardTime);
			}
			ipStatus.put(item.getDeviceIp(),0);
		});	
	}
	
	//发送数据
	private void sendData(List<Map<String, Object>> datas) {
		if(datas!=null && datas.size()>0) {
			log.info("【DOOR推送响应】-->{}",JsonUtil.toString(datas));			
			HttpResponse res = HttpRequest.post(doorConfig.getPushUrl()).body(JsonUtil.toString(datas)).execute();
			log.info("【DOOR推送响应】-->{}", res.body());			
		}
	}
	
	public static String getUUId32() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	public static Long getCurrentTimestamp() {
		return System.currentTimeMillis();
	}
	
	private List<Map<String, Object>> getDatas(DvIntellifHikvisonDevice device){
		List<Map<String, Object>> datas = null;
		try {
			datas = new DoorSdks(device,userIdHeads,ipStatus,minioFrame).start(1,50);
			if(datas!=null) {
				datas.forEach((item)->{
					item.put("id",getUUId32());
					item.put("tenantId",device.getSchoolId());
					item.put("deviceIp",device.getDeviceIp());
					item.put("deviceName",device.getDeviceName());
					item.put("deviceType",device.getDeviceType());
					item.put("deviceAddress",device.getDeviceAddress());
					item.put("createTime",getCurrentTimestamp());
					item.put("updateTime",getCurrentTimestamp());
				});	
			}
		} catch (IOException e) {
			e.printStackTrace();
		}	
		return datas;
	}
	
	//发送状态
	private void sendStatus(String ip){
		Integer status=ipStatus.get(ip);
		log.info("【DOOR推送状态】-->ip:{},status{}",ip,(status==null || status==0)?"离线":"在线");
		if(status!=null) {
			HttpResponse res = HttpRequest.get(doorConfig.getStatusUrl()+"?ip="+ip+"&status="+status).execute();
			log.info("【DOOR推送状态响应】-->{}", res.body());			
		}
	}
 
		
}
